package com.ling.core.view.builder;

import com.bstek.dorado.view.widget.grid.Column;
import com.bstek.dorado.view.widget.grid.ColumnGroup;
import com.bstek.dorado.view.widget.grid.DataColumn;
import com.ling.core.view.ViewComponent;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @author bo.wang
 * @since 2013-2-18
 */
@Component
public class ColumnBuilder extends AbstractControlBuilder {
    public void build(Object control, ViewComponent parentViewComponent) {
        Column column = (Column) control;
        String id = column.getName();
        ViewComponent component = null;
        if (StringUtils.isNotEmpty(id)) {
            component = this.generateViewComponent(id, DataColumn.class);
            if (StringUtils.isNotEmpty(column.getCaption())) {
                component.setDesc(column.getCaption());
            }
        } else if (StringUtils.isNotEmpty(column.getCaption())) {
            component = this.generateViewComponent(column.getCaption(), DataColumn.class);
        } else if (column instanceof DataColumn) {
            DataColumn dc = (DataColumn) column;
            if (StringUtils.isNotEmpty(dc.getProperty())) {
                component = this.generateViewComponent(dc.getProperty(), DataColumn.class);
            }
        }
        if (component != null) {
            if (StringUtils.isEmpty(component.getId())) {
                component.setEnabled(false);
            }
            parentViewComponent.addChildren(component);
        }
        if (column instanceof ColumnGroup) {
            for (Column col : ((ColumnGroup) column).getColumns()) {
                for (IControlBuilder builder : builders) {
                    if (builder.support(col)) {
                        builder.build(col, component);
                        break;
                    }
                }
            }
        }
    }

    public boolean support(Object control) {
        return control instanceof Column;
    }

}
